package com.pdf.pdfserver.service.read.text;

import com.pdf.pdfserver.enums.FileSuffixEnum;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;

/**
 * @Author songfz
 * @Description
 * @Date 2022/1/4
 */
@Service
public class DocReadService implements IfReadService {

    private static Logger LOG = LoggerFactory.getLogger(IfReadService.class);

    @Override
    public String read(FileSuffixEnum suffixEnum, InputStream fis)  {

        WordExtractor ex = null;
        XWPFWordExtractor xex = null;
        try {
            if (FileSuffixEnum.DOC.compareTo(suffixEnum) == 0) {
                ex = new WordExtractor(fis);
                return ex.getText();


            } else if (FileSuffixEnum.DOCX.compareTo(suffixEnum) == 0) {
                XWPFDocument xdoc = new XWPFDocument(fis);
                xex = new XWPFWordExtractor(xdoc);
                return xex.getText();

            }
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        } finally {
            Optional.ofNullable(ex).ifPresent(wordExtractor -> {
                try {
                    wordExtractor.close();
                } catch (IOException e) {
                    LOG.error(e.getMessage(),e);
                }
            });
           Optional.ofNullable(xex).ifPresent(xex1-> {
               try {
                   xex1.close();
               } catch (IOException e) {
                   LOG.error(e.getMessage(),e);
               }
           });
            Optional.ofNullable(fis).ifPresent(in1-> {
                try {
                    in1.close();
                } catch (IOException e) {
                    LOG.error(e.getMessage(),e);
                }
            });
        }

        return null;
    }

}
